<?php

namespace app\shop\controller\statistics;

use app\common\model\supplier\SupplierCommissionWithdrawal;
use app\shop\controller\Controller;
use app\shop\service\statistics\SupplierService;
use app\common\model\supplier\SupplierCommission;
use app\common\model\supplier\CommissionConfig;
/**
 * 供应商数据控制器
 */
class Supplier extends Controller
{
    /**
     * 会员数据统计
     */
    public function index()
    {
        return $this->renderSuccess('', [
            // 供应商统计
            'supplier' => (new SupplierService())->getData(),
        ]);
    }

    /**
     * 通过时间段查询
     * $type类型：new refund
     */
    public function data($search_time)
    {
        $days = $this->getDays($search_time);
        $data = (new SupplierService())->getDataByDate($days);
        return $this->renderSuccess('', [
            // 日期
            'days' => $days,
            // 数据
            'data' => $data,
        ]);
    }

    /**
     * 获取具体日期数组
     */
    private function getDays($search_time)
    {
        //搜索时间段
        if(!isset($search_time) || empty($search_time)){
            //没有传，则默认为最近7天
            $end_time = date('Y-m-d', time());
            $start_time = date('Y-m-d', strtotime('-7 day',time()));
        }else{
            $start_time = array_shift($search_time);
            $end_time = array_pop($search_time);
        }

        $dt_start = strtotime($start_time);
        $dt_end = strtotime($end_time);
        $date = [];
        $date[] = date('Y-m-d', strtotime($start_time));
        while($dt_start < $dt_end) {
            $date[] = date('Y-m-d', strtotime('+1 day',$dt_start));
            $dt_start = strtotime('+1 day',$dt_start);
        }
        return $date;
    }

    public  function getSupplierCommissionList(){
        $params = $this->postData();
        $shop_supplier_id = $params['shop_supplier_id'];
        if(!$shop_supplier_id){
            $jjjshop_supplier_multi = session('jjjshop_supplier_multi');
            $shop_supplier_id = $jjjshop_supplier_multi['user']['shop_supplier_id']??0;

        }
        $data = SupplierCommission::getSupplierCommissionList($shop_supplier_id,$params);
        return $this->renderSuccess('', compact('data'));
    }

   public function withdrawal(){
       $params = $this->postData();
       $shop_supplier_id = $params['shop_supplier_id'];
       $money =  $params['money']??0;
       $payment_images =  $params['payment_images']??'';

       $jjjshop_store_multi = session('jjjshop_store_multi');
       $shop_user_id = $jjjshop_store_multi['user']['shop_user_id']??0;
       if(!$payment_images){
           return $this->renderError('请上传打款凭证');
       }
       $res = (new SupplierCommission()) -> withdrawal($shop_supplier_id,$money,$shop_user_id,1,$payment_images);
       if($res['status'] == 1){
           return $this->renderSuccess($res['msg']);
       }else{
           return $this->renderError($res['msg']);
       }
   }


   public function confirmWithdrawal(){
       $params = $this->postData();
       $shop_supplier_id = $params['shop_supplier_id'];
       $map = [];
       $map[] = ['shop_supplier_id','=',$shop_supplier_id];
       $map[] = ['status','=',0];
       $withdrawal_data = (new SupplierCommissionWithdrawal()) -> where($map) -> find();

       $payment_images =  $params['payment_images']??'';
       if(!$payment_images){
           return $this->renderError('请上传打款凭证');
       }
       if($withdrawal_data){
            $commission_withdrawal_id = $withdrawal_data['commission_withdrawal_id'];
            $update_data['status'] = 1;
            $update_data['payment_images'] = $params['payment_images'];
            (new SupplierCommissionWithdrawal()) -> where('commission_withdrawal_id',$commission_withdrawal_id) -> update($update_data);
            return $this->renderSuccess('操作成功');
       }else{
            return $this->renderError('数据不存在');
       }
   }

    /**
     *拒绝
     * refuse
     * \think\response\Json
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author kevin
     * @date 2024/6/14 12:08
     */
   public function refuse()
   {
       $params = $this->postData();
       $shop_supplier_id = $params['shop_supplier_id'];
       $map = [];
       $map[] = ['shop_supplier_id','=',$shop_supplier_id];
       $map[] = ['status','=',0];
       $withdrawal_data = (new SupplierCommissionWithdrawal()) -> where($map) -> find();

       $remarks =  $params['remarks']??'';
       if(!$remarks){
           return $this->renderError('请填写拒绝原因');
       }
       if($withdrawal_data){
           $commission_withdrawal_id = $withdrawal_data['commission_withdrawal_id'];
           $update_data['status'] = 2;
           $update_data['remarks'] = $params['remarks'];
           (new SupplierCommissionWithdrawal()) -> where('commission_withdrawal_id',$commission_withdrawal_id) -> update($update_data);
           return $this->renderSuccess('操作成功');
       }else{
           return $this->renderError('数据不存在');
       }
   }

   public function getWithdrawalList(){
       $params = $this->postData();
        if(!$params['shop_supplier_id']){
            $jjjshop_supplier_multi = session('jjjshop_supplier_multi');
            $shop_supplier_id = $jjjshop_supplier_multi['user']['shop_supplier_id']??0;
            $params['shop_supplier_id'] = $shop_supplier_id;
        }


       $list = SupplierCommissionWithdrawal::getWithdrawalList($params);
       return $this->renderSuccess('', compact('list'));
   }

    /**
     *获取时间列表
     * getDateList
     * \think\response\Json
     * @return \think\response\Json
     * @Author kevin
     * @date 2024/4/25 11:35
     */
   public function getDateList()
   {
       $list = [];
       for ($i=0;$i<3;$i++){
           if($i==0){
               $v['date_time_text'] = date('Y-m-d');

           }else{
               $v['date_time_text'] = date('Y-m-d', strtotime('-'.$i.' day'));
           }
           $array = [$v['date_time_text'],$v['date_time_text']];
           $v['date_time'] = $array;
           $list[$i] = $v;

       }
       return $this->renderSuccess('', compact('list'));
   }

    /**
     *获取分佣配置列表
     * getCommissionConfigList
     * void
     * @return void
     * @Author kevin
     * @date 2024/4/25 11:36
     */
   public function getCommissionConfigList(){
       $list = (new CommissionConfig()) -> select();
       foreach ($list as $key => $value){
           if($value['type']==1){
               if($value['end_moeny'] > 0){
                   $type_text = intval($value['init_money']) .'-'.intval($value['end_moeny']) .'/瓶';
               }else{
                   $type_text = intval($value['init_money']) .'以上/瓶';
               }

               $list[$key]['rate_text'] = $value['title'] . '  ['.$value['rate'].'%]['.$type_text.']';
           }else{
               $list[$key]['rate_text'] = $value['title'] . '  ['.$value['rate'].'%]';
           }
       }
       return $this->renderSuccess('', compact('list'));
   }

    /**
     * 获取商户佣金明细列表
     * getSupplierList
     * void
     * @return void
     * @Author kevin
     * @date 2024/4/29 15:34
     */
    public  function getSupplierCommissionListData(){
        $params = $this->postData();
        $list = SupplierCommission::getSupplierCommissionListData($params);
        return $this->renderSuccess('', compact('list'));
    }

    public  function exportCommission(){
        $params = $this->postData();
        $list = SupplierCommission::getSupplierCommissionListData($params,2);
        $xls_cell = [
            ['shop_supplier_id' , '商户ID'],
            ['region_name' , '所属地区'],
            ['name' , '商户名称'],
            ['link_name' , '联系人'],
            ['link_phone' , '联系电话'],
            ['total_price' , '订单总额'],
            ['total_commission' , '分佣总额（元）'],
            ['fee' , '支付费率(0.6%;元)'],
            ['income_money' , '累计收入(元)'],
            ['withdrawal_money' , '可提现(元)'],
            ['be_confirmed_money' , '提现（待确认）'],

        ];
        $exp_title = '分佣明细' . date('Y-m-d H:i:s');
        exportExcel($exp_title, $xls_cell, $list);

//        return SupplierCommission::exportCommission($list);
    }


}